﻿using System.Security.Claims;
using LF.Shared.Dtos.Input;
using LF.Shared.Dtos.Out;
using LF.Domain.Services;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.ObjectMapping;
using LF.Domain.Entities;
using LF.Application.Helpers;
using Microsoft.AspNetCore.Http;
using LF.Application.Extend;
using Microsoft.AspNetCore.Mvc;
using LF.Common;
using StackExchange.Redis;
using Role = LF.Domain.Entities.Role;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Sys)]
    public class UserService : BaseService, IUserService
    {
        IAppManagerService _appService;
        IUserManagerService _manager;
        IHttpContextAccessor _httpContext;
        IParamConfigManagerService _paramConfigManager;
        
        public UserService(IObjectMapper<LFModule> mapper,
            IHttpContextAccessor httpContext,
            IAppManagerService appService,
            IUserManagerService manager,
            IParamConfigManagerService paramConfigManager,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _appService = appService;
            _manager = manager;
            _httpContext = httpContext;
            _paramConfigManager = paramConfigManager;
        }



        [AllowAnonymous]
        public Result Token(UserInut user)
        {
            var newUser = _appService.GetUser(user.Name);
            if (newUser == null)
            {
                return Error("用户名不存在!");
            }
            if (newUser.Password != user.Pwd.ToFastMd5())
            {
                return Error("密码错误!");
            }

            // 1 定义需要的Cliam信息
            var claims = new[]
            {
                new Claim("Id", newUser.Id.ToString()),
                new Claim("Name", user.Name)
            };
            var token = JwtHelper.Validate(claims);
            return Ok(token);
        }
        [LFAuthorize("获取用户列表", "system:user:list")]
        public Result<UserSearchOut> Users(UserSearch search)
        {
            var result = _manager.All(search.Index, search.PageSize, search.Key,search.DeptId);
            var list = _mapper.Map<List<User>, List<UserOut>>(result);
            if (list != null)
            {
                foreach(var item in list)
                {
                    // 从原始User对象中获取对应的角色信息
                    var user = result.FirstOrDefault(u => u.Id == item.Id);
                    if (user != null && user.UserRoles != null && user.UserRoles.Any())
                    {
                        // 设置角色ID列表
                        item.RoleIds = user.UserRoles.Select(ur => ur.RoleId).ToList();
                        
                        // 设置角色详细信息
                        var roles = new List<RoleOut>();
                        foreach (var userRole in user.UserRoles)
                        {
                            if (userRole.Role != null)
                            {
                                roles.Add(_mapper.Map<Role, RoleOut>(userRole.Role));
                            }
                        }
                        item.Roles = roles;
                    }
                    else
                    {
                        // 确保返回空数组而不是null
                        item.RoleIds = new List<Guid>();
                        item.Roles = new List<RoleOut>();
                    }
                    
                    // 设置部门名称
                    if (item.DeptId.HasValue && user?.Deptment != null)
                    {
                        item.DeptName = user.Deptment.DeptName;
                    }
                }
            }
            var count = _manager.Count(search.Key, search.DeptId);
            return Ok(new UserSearchOut { Items = list, TotalCount = count });
        }

        [LFAuthorize("获取所有用户列表", "system:user:list")]
        [HttpGet("/api/LF/user/all")]
        public Result<List<UserOut>> GetAllUsers(string? key = null, string? deptId = null)
        {
            var result = _manager.GetAllUsers(key, deptId);
            var list = _mapper.Map<List<User>, List<UserOut>>(result);
            
            if (list != null)
            {
                foreach (var item in list)
                {
                    // 从原始User对象中获取对应的角色信息
                    var user = result.FirstOrDefault(u => u.Id == item.Id);
                    if (user != null && user.UserRoles != null && user.UserRoles.Any())
                    {
                        // 设置角色ID列表
                        item.RoleIds = user.UserRoles.Select(ur => ur.RoleId).ToList();
                        
                        // 设置角色详细信息
                        var roles = new List<RoleOut>();
                        foreach (var userRole in user.UserRoles)
                        {
                            if (userRole.Role != null)
                            {
                                roles.Add(_mapper.Map<Role, RoleOut>(userRole.Role));
                            }
                        }
                        item.Roles = roles;
                    }
                    else
                    {
                        // 确保返回空数组而不是null
                        item.RoleIds = new List<Guid>();
                        item.Roles = new List<RoleOut>();
                    }
                    
                    // 设置部门名称
                    if (item.DeptId.HasValue && user?.Deptment != null)
                    {
                        item.DeptName = user.Deptment.DeptName;
                    }
                }
            }
            
            return Ok(list ?? new List<UserOut>());
        }

        [LFAuthorize("删除用户", "system:user:delete")]
        public Result RealDelete(Guid id)
        {
            if (_manager.RealDelete(id))
                return Ok();
            else
                return Error("保存失败!");
        }

        [LFAuthorize("获取用户信息", "system:user:read")]
        public Result<UserOut> Get(Guid id)
        {
            var user = _manager.Get(id);
            var result = _mapper.Map<User, UserOut>(user);
            
            // 从已加载的UserRoles获取角色信息
            if (user.UserRoles != null && user.UserRoles.Any())
            {
                // 设置角色ID列表
                result.RoleIds = user.UserRoles.Select(ur => ur.RoleId).ToList();
                
                // 设置角色详细信息
                var roles = new List<RoleOut>();
                foreach (var userRole in user.UserRoles)
                {
                    if (userRole.Role != null)
                    {
                        roles.Add(_mapper.Map<Role, RoleOut>(userRole.Role));
                    }
                }
                result.Roles = roles;
            }
            else
            {
                // 确保返回空数组而不是null
                result.RoleIds = new List<Guid>();
                result.Roles = new List<RoleOut>();
            }
            
            // 设置部门名称
            if (result.DeptId.HasValue && user.Deptment != null)
            {
                result.DeptName = user.Deptment.DeptName;
            }
            
            return Ok(result);
        }
        [LFAuthorize("创建编辑用户", "system:user:create")]
        public Result Edit(UserOut user)
        {
            if (!user.Mobile.IsMobile())
            {
                return Error("手机号格式错误");
            }
            bool result;
            var model = _mapper.Map<UserOut, User>(user);
            model.UpdateTime = DateTime.Now;
            var userroles = new List<UserRole>();
            
            
            var any = _appService.GetOldUser(user.UserName);
            if (any != null && any.UserName == user.UserName)
            {
                if (user.Id == null || user.Id != any.Id)
                    return Error("用户已存在!");
            }
            if (user.Id == null)
            {
                // 获取默认密码参数配置
                var defaultPwdConfig = _paramConfigManager.GetByKey("default_password");
                string defaultPwd = defaultPwdConfig != null ? defaultPwdConfig.Value : "Aa12345"; // 使用配置值，如果不存在则使用默认值
                
                model.Password = defaultPwd.ToFastMd5();
                
                model.Id = Guid.NewGuid();
                model.CreatTime = DateTime.Now;
                result = _manager.Insert(model);
                if (user.RoleIds != null && user.RoleIds.Any())
                {
                    foreach (var item in user.RoleIds)
                    {
                        userroles.Add(new UserRole { UserId = model.Id, RoleId = item });
                    }
                    _globalManager.Insert(userroles);
                }
            }
            else
            {
                var old = _manager.Get(user.Id.Value);
                old.DeptId = model.DeptId;
                old.UserName = model.UserName;
                old.RealName = model.RealName;
                old.Mobile = model.Mobile;
                old.Email = model.Email;
                old.Gender = model.Gender;
                old.Active = model.Active;
                //model.Password = old.Password;
                //model.Avatar = model.Avatar??old.Avatar;
                //model.Introduction = old.Introduction;
                //model.Address = model.Address;
                //model.AddressLat = old.AddressLat;
                //model.AddressLng = old.AddressLng;
                //model.Province = old.Province;
                //model.City = old.Province;
                //model.District = old.District;
                //model.Signature = old.Signature;
                result = _manager.Update(old);
                _globalManager.RealDeleteByWhere<UserRole>(p => p.UserId == model.Id);
                if (user.RoleIds != null && user.RoleIds.Any())
                {
                    foreach (var item in user.RoleIds)
                    {
                        userroles.Add(new UserRole { UserId = model.Id, RoleId = item });
                    }
                    _globalManager.Insert(userroles);
                }
            }
            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        public Result<List<UserRoleOut>> GetRoles(Guid id)
        {
            var list = _manager.Roles(id);
            var result = _mapper.Map<List<UserRole>, List<UserRoleOut>>(list);
            return Ok(result);
        }

        public Result PostRoles(List<UserRoleOut> roles)
        {
            if (roles?.Count == 0)
            {
                return Error("没有任何数据!");
            }
            var list = _mapper.Map<List<UserRoleOut>, List<UserRole>>(roles!);
            _manager.ClearRoles(roles!.First().UserId);
            var result = _manager.AddRoles(list);
            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        public Result<List<RoleMenuOut>> Menus()
        {
            var id = _httpContext.HttpContext!.User.GetUserId();
            if (id == null)
            {
                return Error<List<RoleMenuOut>>("非法访问");
            }
            var list = _manager.Menus(id.Value);
            var menus = _mapper.Map<List<RoleMenu>, List<RoleMenuOut>>(list!);
            return Ok(menus);
        }

        [LFAuthorize("重置密码", "system:user:resetpwd")]
        [HttpGet]
        public Result ResetPwd(Guid id)
        {
            // 获取默认密码参数配置
            var defaultPwdConfig = _paramConfigManager.GetByKey("default_password");
            string defaultPwd = defaultPwdConfig != null ? defaultPwdConfig.Value : "Aa12345"; // 使用配置值，如果不存在则使用默认值
            
            var pwd = defaultPwd.ToFastMd5();
            var result = _manager.ResetPwd(id, pwd);
            if (result)
                return Ok();
            else
                return Error("重置失败!");
        }

        public Result<UserOut> GetCurrent()
        {
            var id = _httpContext.HttpContext!.User.GetUserId();
            if (id == null)
            {
                return Error<UserOut>("非法访问");
            }
            return Get(id.Value);
        }
        [HttpPost]
        public Result Delete(Guid[] ids)
        {
            if (ids?.Length < 1)
            {
                return Error("请选择");
            }
            var result = _globalManager.DeleteByWhere<User>(p => ids!.Contains(p.Id));
            if (result)
                return Ok();
            else
                return Error("删除失败!");
        }
        
        /// <summary>
        /// 修改用户密码（需验证旧密码）
        /// </summary>
        [HttpPost]
        public Result ChangePassword(ChangePasswordInut input)
        {
            var userId = _httpContext.HttpContext!.User.GetUserId();
            if (userId == null)
            {
                return Error("非法访问");
            }
            
            // 加密旧密码和新密码
            var oldPasswordEncrypted = input.OldPassword.ToFastMd5();
            var newPasswordEncrypted = input.NewPassword.ToFastMd5();
            
            // 调用领域服务修改密码
            var result = _manager.ChangePassword(userId.Value, oldPasswordEncrypted, newPasswordEncrypted);
            
            if (result)
                return Ok();
            else
                return Error("密码修改失败，请确认旧密码是否正确");
        }
        
        /// <summary>
        /// 保存用户签名MD5值
        /// </summary>
        //[LFAuthorize("保存签名", "system:user:signature")]
        public Result SaveSignature(SignatureInput input)
        {
            var userId = _httpContext.HttpContext!.User.GetUserId();
            if (userId == null)
            {
                return Error("非法访问");
            }
            
            if (string.IsNullOrEmpty(input.SignatureMd5))
            {
                return Error("签名数据不能为空");
            }
            
            try
            {
                // 获取当前用户
                var user = _manager.Get(userId.Value);
                if (user == null)
                {
                    return Error("用户不存在");
                }
                
                // 更新用户签名MD5值
                user.Signature = input.SignatureMd5;
                
                // 保存更新
                var result = _manager.Update(user);
                
                if (result)
                    return Ok();
                else
                    return Error("保存签名失败");
            }
            catch (Exception ex)
            {
                return Error($"保存签名异常：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 删除用户签名
        /// </summary>
        [LFAuthorize("删除签名", "system:user:signature")]
        public Result RemoveSignature()
        {
            var userId = _httpContext.HttpContext!.User.GetUserId();
            if (userId == null)
            {
                return Error("非法访问");
            }
            
            try
            {
                // 获取当前用户
                var user = _manager.Get(userId.Value);
                if (user == null)
                {
                    return Error("用户不存在");
                }
                
                // 删除用户签名MD5值
                user.Signature = string.Empty;
                
                // 保存更新
                var result = _manager.Update(user);
                
                if (result)
                    return Ok();
                else
                    return Error("删除签名失败");
            }
            catch (Exception ex)
            {
                return Error($"删除签名异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 保存用户基础信息（仅基础信息字段）
        /// </summary>
        [HttpPost("/api/LF/user/save-basic-info")]
        public Result SaveBasicInfo(UserBasicInfoInput input)
        {
            var userId = _httpContext.HttpContext!.User.GetUserId();
            if (userId == null)
            {
                return Error("非法访问");
            }

            var user = _manager.Get(userId.Value);
            if (user == null)
            {
                return Error("用户不存在");
            }

            // 只更新基础信息字段
            user.Avatar = input.Avatar;
            user.RealName = input.RealName;
            user.Mobile = input.Mobile;
            user.Email = input.Email;
            user.Province = input.Province;
            user.City = input.City;
            user.District = input.District;
            user.Address = input.Address;
            user.AddressLng = input.AddressLng;
            user.AddressLat = input.AddressLat;
            user.Introduction = input.Introduction;
            user.UpdateTime = DateTime.Now;

            var result = _manager.Update(user);
            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        /// <summary>
        /// 获取当前用户信息（提供给第三方登录调用）
        /// </summary>
        [HttpGet]
        public Result<UserOut> GetUserInfo()
        {
            var userId = _httpContext.HttpContext!.User.GetUserId();
            if (userId == null)
            {
                return Error<UserOut>("非法访问");
            }
            
            // 复用现有的Get方法逻辑
            return Get(userId.Value);
        }
    }
}

